import { Component, OnInit, Inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { TranslateService } from '@ngx-translate/core';
import { RestService } from '../../services/rest.service';
import { ActionTypes } from '../../models/wdl-types';

import * as _ from 'lodash';

@Component({
  selector: 'app-find-device',
  templateUrl: './find-device.component.html',
  styleUrls: ['./find-device.component.css']
})
export class FindDeviceComponent implements OnInit {
  formGroup: FormGroup;

  item: any;
  institution: any;
  title = '';
  result = '';
  isLoadingResults = false;

  // could be add, modify
  mode = ActionTypes.ADD;
  disabled = false;

  error = '';

  constructor(@Inject(MAT_DIALOG_DATA) private dialogData: any,
              public dialogRef: MatDialogRef<FindDeviceComponent>,
              fb: FormBuilder,
              private translate: TranslateService,
              private rest: RestService) {
    this.institution = dialogData.institution;
    this.mode = dialogData.mode;

    this.title = this.translate.get('add')['value'] + this.translate.get('device')['value'];

    this.formGroup = fb.group({
      deviceId: [
        '',
        [ Validators.required, Validators.minLength(10), Validators.maxLength(10) ]
      ]
    });
  }

  disableSubmit() {
    return this.formGroup.invalid || (this.mode === ActionTypes.MODIFY && !this.formGroup.dirty);
  }

  submit() {
    const data = {};
    _.forEach(this.formGroup.value, (value, key) => {
      data[key] = _.trim(value);
    });

    this.error = '';

    this.isLoadingResults = true;
    this.rest.getWithParams('data/device/search/deviceId', {deviceId: data['deviceId']}).subscribe(resp => {
      if (resp['_embedded']['devices'].length > 0) {
        this.rest.get('data/device/' + resp['_embedded']['devices'][0].id + '/institution').subscribe(inst => {
          this.isLoadingResults = false;
          this.result = this.translate.get('deviceBelongsTo')['value'] + ': ' + inst['instName'];
        }, () => {
          this.isLoadingResults = false;
          this.result = this.translate.get('deviceBelongsTo')['value'];
        });
      } else {
        this.isLoadingResults = false;
        this.result = this.translate.get('noDeviceFound')['value'];
      }
    }, () => {
      this.isLoadingResults = false;
      this.result = this.translate.get('noDeviceFound')['value'];
    });
  }

  ngOnInit() {
  }
}
